package com.bnzj.cloud.business.core.service;

import java.util.Date;

import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.bnzj.cloud.business.core.persistence.entity.ProcessNumber;
import com.bnzj.cloud.business.core.persistence.repository.ProcessNumberRepository;
import com.bnzj.core.persistence.BaseService;
import com.bnzj.core.util.DateUtils;
import com.bnzj.core.util.FbConstant;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class ProcessNumberService extends BaseService<ProcessNumberRepository, ProcessNumber, Long> {

	public String queryByKeyDate(String keyDate) {
		return repository.queryByKeyDate(keyDate);
	}
	
	public void insertProcessNumber(String processNumber) {
		repository.insertProcessNumber(processNumber);
	}
	
	/**
	 * 序列生成器 key+yyyymmdd+0000
	 * @param key
	 * @return
	 */
	@Transactional
	public String creatProcessNumber(String key) {
		try {
			synchronized(key) {
				String date = DateUtils.formatDate(new Date(), FbConstant.DATESTR_FORMAT);
				String data = this.queryByKeyDate(key + date);
				if(null==data) {
					data = "0001";
				}else {
					while(data.length()<4) {
						data = "0" + data;
					}
				}
				this.insertProcessNumber(key + date + data);
		    	return key + date + data;
			}
		}catch(Exception e) {
			log.error("创建流程单号异常",e);
		}
		return null;
    }
	
}
